package com.fizzkai.p2p.core.service.impl;

import com.fizzkai.p2p.core.domain.LoginInfo;
import com.fizzkai.p2p.core.domain.OrderTime;
import com.fizzkai.p2p.core.domain.UserInfo;
import com.fizzkai.p2p.core.domain.VideoAuth;
import com.fizzkai.p2p.core.exception.DisplayableException;
import com.fizzkai.p2p.core.mapper.VideoAuthMapper;
import com.fizzkai.p2p.core.query.QueryObject;
import com.fizzkai.p2p.core.service.ILoginInfoService;
import com.fizzkai.p2p.core.service.IOrderTimeService;
import com.fizzkai.p2p.core.service.IUserInfoService;
import com.fizzkai.p2p.core.service.IVideoAuthService;
import com.fizzkai.p2p.core.util.AssertUtil;
import com.fizzkai.p2p.core.util.BitStateUtil;
import com.fizzkai.p2p.core.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service@Transactional
public class VideoAuthServiceImpl implements IVideoAuthService {

    @Autowired
    private VideoAuthMapper videoAuthMapper;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private ILoginInfoService loginInfoService;
    @Autowired
    private IOrderTimeService timeService;

    @Override
    public int saveOrUpdate(VideoAuth entity) {
        int row;
        if (entity.getId() == null) {
            row = videoAuthMapper.insert(entity);
        } else {
            row = videoAuthMapper.updateByPrimaryKey(entity);
        }
        return row;
    }

    @Override
    public VideoAuth get(Long id) {
        return videoAuthMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo<VideoAuth> query(QueryObject qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        List<VideoAuth> list = videoAuthMapper.queryList(qo);
        return new PageInfo<>(list);
    }

    @Override
    public void apply(Long timeid, String orderDate, Long auditorId) {
        AssertUtil.allNotNull("非法参数", timeid,  orderDate,  auditorId);
        LoginInfo auditor = loginInfoService.get(auditorId);
        OrderTime orderTime = timeService.get(timeid);
        AssertUtil.allNotNull("非法参数", auditor, orderTime);
        // 判断 原来得 UserInfo
        UserInfo userInfo = userInfoService.getCurrent();
        if (userInfo.isHasVideoAuth()) {
            throw new DisplayableException("您已经通过视频验证了，无需重复申请");
        }
        if (userInfo.getVideoAuthId() != null) {
            throw new DisplayableException("您申请的认证正在审核中，无需重复提交");
        }
        //
        VideoAuth videoAuth = new VideoAuth();
        videoAuth.setApplier(UserContext.getCurrentLoginInfo());
        videoAuth.setApplyTime(new Date());
        videoAuth.setAuditor(auditor);
        videoAuth.setState(VideoAuth.STATE_NORMAL);
        // 设置 预约时间
        String beginDateStr = orderDate + " " + orderTime.getBegin();
        String endDateStr = orderDate + " " + orderTime.getEnd();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            videoAuth.setOrderBeginDate(format.parse(beginDateStr));
            videoAuth.setOrderEndDate(format.parse(endDateStr));
        } catch (Exception ex) {
            throw new DisplayableException("非法参数");
        }
        // 保存 videoAuth
        saveOrUpdate(videoAuth);
        // 保存 UserInfo
        userInfo.setVideoAuthId(videoAuth.getId());
        userInfoService.update(userInfo);
    }

    @Override
    public void audit(Long videoAuthId, Integer state, String remark) {
        // 拦截 非法状态
        AssertUtil.allNotNull("参数错误", videoAuthId, state);
        VideoAuth videoAuth = videoAuthMapper.selectByPrimaryKey(videoAuthId);
        AssertUtil.isNotNull(videoAuth, "找不到该审核单");
        if (videoAuth.getState() != VideoAuth.STATE_NORMAL) {
            throw new DisplayableException("该审核单已经审核，无需重复提交");
        }
        Long userId = videoAuth.getApplier().getId();
        UserInfo userInfo = userInfoService.get(userId);
        AssertUtil.isNotNull(userInfo, "找不到被审核用户");
        // 设置 审核状态
        if (state.equals(VideoAuth.STATE_PASS)) {
            // pass
            videoAuth.setState(VideoAuth.STATE_PASS);
            userInfo.addState(BitStateUtil.HAS_VIDEOAUTH);
        } else {
            // reject
            videoAuth.setState(VideoAuth.STATE_REJECT);
            userInfo.setVideoAuthId(null);
        }
        // 设置 审核时间 + 审核人
        videoAuth.setAuditor(UserContext.getCurrentLoginInfo());
        videoAuth.setAuditTime(new Date());
        videoAuth.setRemark(remark);
        // 保存 userInfo
        userInfoService.update(userInfo);
        // 保存 video
        videoAuthMapper.updateByPrimaryKey(videoAuth);
    }
}
